import React, { useEffect } from 'react';
import { useParams, useNavigate, useLocation } from 'react-router-dom';
import { useTranslation } from 'react-i18next';

interface LanguageRouteWrapperProps {
  children: React.ReactNode;
}

const LanguageRouteWrapper: React.FC<LanguageRouteWrapperProps> = ({ children }) => {
  const { lang } = useParams<{ lang: string }>();
  const { i18n } = useTranslation();
  const navigate = useNavigate();
  const location = useLocation();

  useEffect(() => {
    const supportedLanguages = ['zh', 'th'];
    
    if (lang && supportedLanguages.includes(lang)) {
      // 如果 URL 中有有效的语言代码，设置语言
      if (i18n.language !== lang) {
        i18n.changeLanguage(lang);
      }
    } else {
      // 如果没有语言代码或语言代码无效，重定向到默认语言
      const currentLang = i18n.language || 'zh';
      const pathWithoutLang = location.pathname.replace(/^\/(zh|th)/, '');
      const newPath = `/${currentLang}${pathWithoutLang}`;
      
      if (newPath !== location.pathname) {
        navigate(newPath + location.search + location.hash, { replace: true });
      }
    }
  }, [lang, i18n, navigate, location]);

  return <>{children}</>;
};

export default LanguageRouteWrapper;
